package com.uxsino.rule.nms.validate;

import com.google.common.primitives.Floats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uxsino.rule.model.ExistsCompareWay;

public class ExistValidator extends BaseValidate {
    private static Logger logger = LoggerFactory.getLogger(ExistValidator.class);

    private ExistsCompareWay compareWay;

    private String value;

    private String target;

    public ExistValidator(ExistsCompareWay compareWay, String value, String target) {
        this.compareWay = compareWay;
        this.value = value;
        this.target = target;
    }

    /**
     *
     * @return true-告警，false-不告警
     */
    @Override
    public boolean validate() {
        if (compareWay == null) {
            logger.error("Exist validate -> CompareWay is null!");
            return false;
        }
        if (value == null) {
            logger.error("Exist validate -> Value is null!");
            return false;
        }
        if (target == null) {
            logger.error("Exist validate -> Target is null!");
            return false;
        }
        switch (compareWay) {
        case exists:
            if (Floats.tryParse(target) != null && Floats.tryParse(value) != null) {
                return Floats.tryParse(target).equals(Floats.tryParse(value));
            }
            return target.equals(value);
        case notexists:
            return existsCompare_and(value, target);
        default:
            break;
        }
        return false;
    }

    private boolean existsCompare_and(String value, String target) {
        String[] targetArry = target.split(",");
        boolean temp = true;
        for (String str : targetArry) {
            if (Floats.tryParse(str) != null && Floats.tryParse(value) != null) {
                if (Floats.tryParse(value).equals(Floats.tryParse(str))) {
                    temp = false;
                    break;
                }
            }else {
                if (value.equals(str)) {
                    temp = false;
                    break;
                }
            }
        }
        return temp;
    }

}
